package com.utils
{
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;

	public class TextFieldUtil
	{
		public static var TEXT_FONT_NAME:String = "";
		public static var TEXT_FONT_SIZE:int = 14;
		
		public static var NUMBER_FONT_NAME:String = "";
		public static var NUMBER_FONT_SIZE:int = 14;
		
		public static function setText(textField:TextField, text:String, number:Boolean = false, font:String = "", size:int = 0):void
		{
			if(textField == null) return;
			
			var textFormat:TextFormat;
			
			var textFont:String;
			var textSize:int;
			
			if(textField.defaultTextFormat != null)
			{
				textFormat = createTextFormat(textField.defaultTextFormat);
			}else{
				textFormat = new TextFormat();
			}
			
			if(!number){
				textFont = TEXT_FONT_NAME;
				textSize = TEXT_FONT_SIZE;
			}else{
				textFont = NUMBER_FONT_NAME;
				textSize = NUMBER_FONT_SIZE;
			}
			
			if(font != "") textFont = font;
			if(size != 0) textSize = size;
			
			textFormat.font = textFont;
			textFormat.size = textSize;
			
			textField.defaultTextFormat = textFormat;
			
			textField.text = text;
		}
		
		public static function setHtmlText(textField:TextField, htmlText:String, number:Boolean = false, 
										      font:String = "Verdana", size:int = 0):void
		{
			if(textField == null) return;
			
			var textFont:String;
			var textSize:int;
			
			if(!number){
				textFont = TEXT_FONT_NAME;
				textSize = TEXT_FONT_SIZE;
			}else{
				textFont = NUMBER_FONT_NAME;
				textSize = NUMBER_FONT_SIZE;
			}
			
			if(font != "") textFont = font;
			if(size != 0) textSize = size;
				
			textField.htmlText = "<font face = \"" + textFont + "\" size = \"" + textSize + "\">" + htmlText + "</font>";
		}
		
		private static function createTextFormat(textFormat:TextFormat):TextFormat
		{
			var newFormat:TextFormat = new TextFormat();
			
			for(var key:String in textFormat)
			{
				newFormat[key] = textFormat[key];
			}
			
			return newFormat;
		}
		
		/**
		 * 添加文本
		 * @param targetContain 文本容器
		 * @param params 要设置的属性
		 */		
		public static function newTextField(parentContain:Sprite=null,str:String='',params:Object=null,color:String = '',size:int = 0,font:String = 'Verdana'):TextField
		{
			var txt:TextField = new TextField();
			txt.textColor = 0xFFFFFF;
			for(var key:String in params)
			{
				txt[key] = params[key];
			}
			var size:int = size==0 ? 12:size;
			var color:String = color==''? '#FFFFFF':color;
			txt.htmlText = '<font face="'+font+'" size="'+size+'" color="'+color+'">'+ str +'</font>';
			txt.height = txt.textHeight+5;
			if(parentContain) parentContain.addChild(txt);
			return txt;
		}
		
		
		
		
		
		
		
		
		
	}
}